"""
本文详细阐述了Assistant API中Run类的各项功能，涵盖了运行任务的创建、列举、检索、修改、提交工具输出以及等待运行任务结束等操作。
"""
import dashscope
from dashscope import Assistants
from dashscope import Threads
from dashscope import Steps
from dashscope import Runs
import os
import json
assistant = Assistants.create(
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        model='qwen-max',
        name='smart helper',
        description='A tool helper.',
        instructions='You are a helpful assistant. When asked a question, use tools wherever possible.',
        tools=[{
            'type': 'search'
        }, {
            'type': 'function',
            'function': {
                'name': 'big_add',
                'description': 'Add to number',
                'parameters': {
                    'type': 'object',
                    'properties': {
                        'left': {
                            'type': 'integer',
                            'description': 'The left operator'
                        },
                        'right': {
                            'type': 'integer',
                            'description': 'The right operator.'
                        }
                    },
                    'required': ['left', 'right']
                }
            }
        }],
)
thread = Threads.create(messages=[{"role": "user", "content": "How does AI work? Explain it in simple terms."}])
print('创建运行任务,流式任务代码示例')
stream_iterator = dashscope.Runs.create(thread.id,
                                    assistant_id=assistant.id,
                                    stream=True)
for event, msg in stream_iterator:
    print(event)
    print(msg)
print('创建线程和运行任务')
run = Runs.create(thread.id,
                  assistant_id=assistant.id,
                  model='qwen-max',
                  instructions='Instructions',
                  additional_instructions='additional_instructions',
                  tools=[{'type': 'code_interpreter'}],
                  metadata={'key': 'value'})
print(json.dumps(run, default=lambda o: o.__dict__, sort_keys=True, indent=4))
print('列出运行任务')
runs = Runs.list(thread.id,
                 limit=1,
                 order='desc',
                 after='',
                 before='')
print(json.dumps(runs, default=lambda o: o.__dict__, sort_keys=True, indent=4))
print('列出运行任务的关联步骤')
steps = Steps.list(run.id,
                   thread_id=thread.id,
                   limit=10)
print(json.dumps(steps, default=lambda o: o.__dict__, sort_keys=True, indent=4))
print('检索运行任务')
run = Runs.retrieve(run.id,
                    thread_id=thread.id)
print(json.dumps(run, default=lambda o: o.__dict__, sort_keys=True, indent=4))